<?php

namespace App\Kuafu\Order\Jobs;

use App\Kuafu\Common\Jobs\SensorsDataJob;
use App\Kuafu\Common\Service\CommonService;
use App\Kuafu\Coupon\Enum\CouponEnum;
use App\Kuafu\Coupon\Model\CouponModel;
use App\Kuafu\CustomerCoupon\Model\CustomerCouponModel;
use App\Kuafu\Order\Enum\CodeEnum;
use App\Kuafu\Order\Model\OrderCouponSplitModel;
use App\Kuafu\Order\Model\OrderDetailSplitModel;
use App\Kuafu\Order\Model\OrderExternalSplitModel;
use App\Kuafu\Order\Model\OrderSplitModel;
use App\Kuafu\Shop\Service\ShopService;
use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Foundation\Mix;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;


/**
 * @description 提交｜取消订单消息队列
 *
 * @queueName {SUBMIT-OR-CANCEL-ORDER-QUEUE}
 */
class SubmitOrCancelOrderJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * 异常标题
     */
    const EXCEPTION_TITLE = '【 消费队列 】【 提交｜取消订单 】';

    /**
     * 队列名称
     *
     * @var string
     */
    public static string $QUEUE_NAME = '{RMS-SUBMIT-OR-CANCEL-ORDER-QUEUE}';

    /**
     * 门店id
     *
     * @var int
     */
    public int $shopId;

    /**
     * 订单id
     *
     * @var int
     */
    public int $orderId;

    /**
     * 取消类型
     *
     * @var
     */
    public $cancelType;

    const TYPE_CANCEL_SELF    = 0;//主动取消
    const TYPE_CANCEL_TIMEOUT = 1;//超时取消

    const TYPE_CANCEL_MAP = [
        self::TYPE_CANCEL_SELF    => '主动取消',
        self::TYPE_CANCEL_TIMEOUT => '超时取消'
    ];

    public int $type;

    const TYPE_CANCEL_ORDER = 0;//取消订单
    const TYPE_SUBMIT_ORDER = 1;//提交订单

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($shopId, $orderId, $type, $cancelType)
    {
        $this->shopId     = $shopId;
        $this->orderId    = $orderId;
        $this->type       = $type;
        $this->cancelType = $cancelType;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {
            list($orderObject, $orderDetailObject, $orderCouponObject, $extOrderObject) = $this->getParams();

            // 新增常去门店处理
            if ($this->type == self::TYPE_SUBMIT_ORDER) {
                ShopService::shopUserUsuallyAdd($orderObject->userId, $this->shopId);
            }

            //丢入神策埋点
//            $this->sensorsDataHandle($orderObject, $orderDetailObject, $orderCouponObject, $extOrderObject);

        } catch (Exception $e) {
            CommonService::fsLogException(self::EXCEPTION_TITLE, $e,
                Collect(get_object_vars($this))->only(['shopId', 'orderId', 'cancelType', 'queue'])->toArray(), true);
        }
    }

    /**
     * @return array
     * @throws Exception
     */
    public function getParams(): array
    {
        $orderObject = OrderSplitModel::suffix($this->shopId)
                                      ->query()
                                      ->where('orderId', $this->orderId)
                                      ->first();
        if (empty($orderObject)) {
            throw new Exception('订单查询失败');
        }

        //获取菜品详情数据
        $orderDetailObject = OrderDetailSplitModel::suffix($this->shopId)
                                                  ->query()
                                                  ->where('orderId', $this->orderId)
                                                  ->get();

        //获取订单优惠券使用
        $orderCouponObject = OrderCouponSplitModel::suffix($this->shopId)
                                                  ->query()
                                                  ->where('orderId', $this->orderId)
                                                  ->get();

        $extOrderObject = OrderExternalSplitModel::suffix($this->shopId)->query()
                                                 ->where('orderId', $this->orderId)
                                                 ->get();

        return [$orderObject, $orderDetailObject, $orderCouponObject, $extOrderObject];
    }


    /**
     * 神策埋点处理
     *
     * @param Model|object|static|null $orderObject
     * @param Collection|static[] $orderDetailObject
     * @param Collection|static[] $orderCouponObject
     * @param Collection|static[] $extOrderObject
     */
    public function sensorsDataHandle($orderObject, $orderDetailObject, $orderCouponObject, $extOrderObject)
    {
     /*   switch ($this->type) {
            case self::TYPE_SUBMIT_ORDER:
                //丢入神策埋点【 提交订单 】
                SensorsDataJob::dispatch(
                    $this->shopId,
                    $orderObject->userId,
                    SensorsDataJob::TYPE_SUBMIT_ORDER,
                    [
                        'order_no'        => (string)$orderObject->orderId,//订单编号 |STRING|
                        'order_amount'    => bcdiv($orderObject->originalPrice, 100, 2),//订单金额 |NUMBER| 菜品总金额：统计所有菜品⾦额=
                        'discount_amount' => bcdiv($orderObject->discountPrice, 100, 2),//优惠折扣 |STRING|
                        'pay_amount'      => bcdiv(
                            $orderObject->orderShouldPrice - $extOrderObject->sum('payPrice'),
                            100, 2),//优惠后金额 |NUMBER| 优惠后的菜品总金额
                    ]
                )->onQueue(SensorsDataJob::$QUEUE_NAME);

                //丢入神策埋点【 提交订单 】【 菜品详情 】
                $orderDetailObject->each(function ($item) use ($orderObject) {
                    SensorsDataJob::dispatch(
                        $this->shopId,
                        $orderObject->userId,
                        SensorsDataJob::TYPE_SUBMIT_ORDER_MENU_DETAIL,
                        [
                            'order_no'           => (string)$item->orderId,
                            //订单编号 |STRING|
                            'menu_type'          => (string)\App\Kuafu\Product\Enum\CodeEnum::TYPE_PRODUCT_TYPE_TEXT[$item->type] ?? '单品',
                            //菜品分类 |STRING| 必吃，素串系列，卤油炸串，套餐类等
                            'menu_name'          => (string)$item->productName,
                            //菜品名称 |STRING| 如果是套餐组合，传套餐名称
                            'menu_originalPrice' => (string)bcdiv($item->originalUnitPrice, 100, 2),
                            //菜品原价 |STRING|
                            'menu_quantity'      => (string)$item->num,
                            //菜品数量 |STRING|
                            'menu_amount'        => bcdiv($item->originalPrice, 100, 2),
                            //菜品金额 |NUMBER| 菜品⾦额默认为菜品原价*菜品份额
                            'discount_amount'    => (string)bcdiv($item->totalDiscountPrice, 100, 2),
                            //优惠折扣 |STRING|
                            'pay_amount'         => bcdiv($item->payPrice, 100, 2),
                            //优惠后金额 |NUMBER| 优惠后的菜品总金额
                        ]
                    )->onQueue(SensorsDataJob::$QUEUE_NAME);
                });

                if ($orderCouponObject) {
                    //获取用户优惠券信息
                    $customCouponObject = CustomerCouponModel::query()
                                                             ->whereIn('id',
                                                                 $orderCouponObject->pluck('customerCouponId')
                                                                                   ->toArray())
                                                             ->get()->keyBy('id');

                    //丢入神策埋点【 优惠券核销 】
                    $orderCouponObject->each(function ($item) use ($orderObject, $customCouponObject) {
                        SensorsDataJob::dispatch(
                            $this->shopId,
                            $orderObject->userId,
                            SensorsDataJob::TYPE_USE_COUPON,
                            [
                                'order_time'       => date('Y-m-d H:i:s', $orderObject->createdAt->timestamp),
                                //订单时间 DATETIME
                                'order_no'         => (string)$item->orderId,
                                //订单编号 |STRING|
                                'user_coupon_id'   => (string)$item->customerCouponId, //用户优惠券id string
                                'coupon_id'        => (string)$item->couponId,
                                //优惠券id STRING
                                'coupon_type'      => (string)CouponEnum::COUPONTYPE[$item->couponType],
                                //优惠券类型 STRING 折扣券，满减券
                                'coupon_name'      => (string)$item->couponName,
                                //优惠券名称 STRING 新人优惠券
                                'coupon_content'   => (string)CouponModel::getCouponDescription(
                                    $item->couponType,
                                    $item->discount,
                                    $item->useCondition
                                ),
                                //优惠券内容 STRING 满xx减xx
                                'coupon_amount'    => bcdiv($item->couponDiscountPrice, 100, 2),
                                //优惠券金额 NUMBER 6
                                'coupon_discount'  => (string)($item->couponType == CouponEnum::COUPON_TYPE_DISCOUNT ?  $item->couponNum : 0),
                                //优惠券折扣 STRING 6.8折
                                'coupon_period'    => (string)(int)($customCouponObject->isEmpty() ?
                                    30 :
                                    (($customCouponObject[$item->customerCouponId]->endAt - $customCouponObject[$item->customerCouponId]->startAt) / (24 * 60 * 60))),
                                //优惠券有效期 STRING
                                'coupon_startDate' => $customCouponObject->isEmpty() ?
                                    date('Y-m-d H:i:s', time()) :
                                    date('Y-m-d H:i:s', $customCouponObject[$item->customerCouponId]->startAt),
                                //优惠券开始日期 DATETIME
                                'coupon_endDate'   => $customCouponObject->isEmpty() ?
                                    date('Y-m-d H:i:s', time() + 30 * 24 * 60 * 60) :
                                    date('Y-m-d H:i:s', $customCouponObject[$item->customerCouponId]->endAt),
                                //优惠券结束日期 DATETIME
                            ]
                        )->onQueue(SensorsDataJob::$QUEUE_NAME);
                    });
                }
                break;
            case self::TYPE_CANCEL_ORDER:
                //丢入神策埋点 【 取消订单 】
                SensorsDataJob::dispatch(
                    $this->shopId,
                    $orderObject->userId,
                    SensorsDataJob::TYPE_CANCEL_ORDER,
                    [
                        'order_no'        => (string)$orderObject->orderId,
                        //订单编号 STRING
                        'order_time'      => date('Y-m-d H:i:s', $orderObject->createdAt->timestamp),
                        //订单时间 DATETIME 提交订单的时间
                        'order_amount'    => bcdiv($orderObject->originalPrice, 100, 2),
                        //订单金额 NUMBER
                        'discount_amount' => bcdiv($orderObject->discountPrice, 100, 2),
                        //优惠折扣 STRING
                        'pay_amount'      => bcdiv($orderObject->orderShouldPrice - $extOrderObject->sum('payPrice'),
                            100, 2),
                        //优惠后金额 NUMBER
                        'cancel_type'     => self::TYPE_CANCEL_MAP[$this->cancelType],
                        //取消类型 STRING 用户主动取消，订单支付超时
                    ]
                )->onQueue(SensorsDataJob::$QUEUE_NAME);

                //丢入神策埋点【 取消订单 】【 菜品详情 】
                $orderDetailObject->each(function ($item) use ($orderObject) {
                    SensorsDataJob::dispatch(
                        $this->shopId,
                        $orderObject->userId,
                        SensorsDataJob::TYPE_CANCEL_ORDER_MENU_DETAIL,
                        [
                            'order_time'         => date('Y-m-d H:i:s', $orderObject->createdAt->timestamp),
                            //订单时间 DATETIME 提交订单的时间
                            'order_no'           => (string)$item->orderId,
                            //订单编号 |STRING|
                            'menu_type'          => (string)\App\Kuafu\Product\Enum\CodeEnum::TYPE_PRODUCT_TYPE_TEXT[$item->type] ?? '单品',
                            //菜品分类 |STRING| 必吃，素串系列，卤油炸串，套餐类等
                            'menu_name'          => $item->productName,
                            //菜品名称 |STRING| 如果是套餐组合，传套餐名称
                            'menu_originalPrice' => bcdiv($item->originalUnitPrice, 100, 2),
                            //菜品原价 |STRING|
                            'menu_quantity'      => $item->num,
                            //菜品数量 |STRING|
                            'menu_amount'        => bcdiv($item->originalPrice, 100, 2),
                            //菜品金额 |NUMBER| 菜品⾦额默认为菜品原价*菜品份额
                            'discount_amount'    => bcdiv($item->discountPrice, 100, 2),
                            //优惠折扣 |STRING|
                            'pay_amount'         => bcdiv($item->payPrice, 100, 2),
                            //优惠后金额 |NUMBER| 优惠后的菜品总金额
                            'cancel_type'        => self::TYPE_CANCEL_MAP[$this->cancelType],//取消类型 STRING 用户主动取消，订单支付超时
                        ]
                    )->onQueue(SensorsDataJob::$QUEUE_NAME);
                });
                break;
        }*/

    }
}
